package com.gouaixin.bee.beeframework2.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;
import android.os.Handler;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ab.activity.AbActivity;
import com.ab.util.AbImageUtil;
import com.ab.util.AbToastUtil;
import com.ab.view.titlebar.AbTitleBar;
import com.gouaixin.bee.beeframework2.MyConfig;
import com.gouaixin.bee.beeframework2.R;
import com.gouaixin.bee.beeframework2.adapter.MsgAdapter;
import com.gouaixin.bee.beeframework2.bean.MSG;
import com.gouaixin.bee.beeframework2.bean.USER;
import com.gouaixin.bee.beeframework2.component.AutoScrollTextView;
import com.gouaixin.bee.beeframework2.model.ChatModel;
import com.gouaixin.bee.beeframework2.dao.MsgDao;
import com.gouaixin.bee.beeframework2.bean.BaseModel;
import com.gouaixin.bee.beeframework2.model.DialogModel;
import com.gouaixin.bee.beeframework2.model.MemberModel;
import com.gouaixin.bee.beeframework2.tool.EmojiFilter;
import com.gouaixin.bee.beeframework2.tool.NetworkUtils;
import com.gouaixin.bee.beeframework2.tool.PreferencesUtils;
import com.gouaixin.bee.beeframework2.tool.XHttpUtils;
import com.gouaixin.bee.beeframework2.tool.mLog;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageLoadingListener;

import org.apache.commons.lang3.StringEscapeUtils;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import cn.bmob.v3.BmobPushManager;

/**
 * Created by Administrator on 2015/3/10.
 */
//聊天消息界面（使用数据库）
public class C2_MsgActivity extends AbActivity {
    Context context = C2_MsgActivity.this;

    String jid = "聊天界面";
    String cid = "";
    String cname = "";
    String flag = "";

    ImageView back;//返回按钮
    TextView title;//标题姓名
    TextView right;//更多

    EditText input;//输入框
    TextView send;//发送按钮

    ListView list;//聊天列表
    List<MSG> datas;
    MsgAdapter adapter;

    RelativeLayout footer;
    RelativeLayout suoyao;

    String jicon = "";//保存的头像网址
    String jname = "";//机器人name
    String qianming = "";//机器人的内心独白
    BmobPushManager bmobPushManager;


    //标题栏
    private AbTitleBar mAbTitleBar = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setAbContentView(R.layout.c1_liaotianjiemian);
        datas = new ArrayList<MSG>();
        bmobPushManager = new BmobPushManager(this);
        adapter = new MsgAdapter(context);
        list = (ListView) findViewById(R.id.list);
        list.setAdapter(adapter);

        initIntent();
        initHead();
        initDubai();
        initFoot();

//        initTitleBar();

        initAutoScrollTextView();//滚动显示


    }

    private TextView mLayout;

    private void initFloatView() {
        mLayout = (TextView) findViewById(R.id.shipingfv);
        mLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                DialogModel.goVIP(context, "你还没有开通VIP，无法视频聊天");
            }
        });

        MemberModel.setGetUserLister(new MemberModel.GetUserLister() {
            @Override
            public void onSuccess(USER user) {
                int viptype = user.getVipType();
                if (viptype > 0) {
                    mLayout.setVisibility(View.INVISIBLE);
                } else {
                    mLayout.setVisibility(View.VISIBLE);
                }
            }

            @Override
            public void onFailure(int i, String s) {

            }
        });
        MemberModel.getUSER(context);
    }


    private void initAutoScrollTextView() {
        //准备滚动显示的文字
        int temp = 6 + new Random().nextInt(5);
        String str = "有" + temp + "名异性10分钟内和" + jname + "打过招呼";

        //启动公告滚动条
        AutoScrollTextView autoScrollTextView = (AutoScrollTextView) findViewById(R.id.TextViewNotice);
        autoScrollTextView.setText(str);
        autoScrollTextView.setBackgroundColor(getResources().getColor(R.color.blank));
        autoScrollTextView.init(getWindowManager());
        autoScrollTextView.startScroll();


    }


    private void initTitleBar() {
        mAbTitleBar = this.getTitleBar();
        View titleBar = mInflater.inflate(R.layout.liaotian_head, null);
        mAbTitleBar.addView(titleBar);


        ImageView title_back = (ImageView) titleBar.findViewById(R.id.back);
        TextView title_text = (TextView) titleBar.findViewById(R.id.title);
        final TextView title_back2 = (TextView) titleBar.findViewById(R.id.back2);

        title_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        title_text.setText(jname);


//        final View popView = mInflater.inflate(R.layout.list_pop, null);
//        ListView popListView = (ListView) popView.findViewById(R.id.pop_list);
//        List<AbMenuItem> list = new ArrayList<AbMenuItem>();
//        list.add(new AbMenuItem("真心话模式"));
//        list.add(new AbMenuItem("送礼物"));
//        list.add(new AbMenuItem("更多"));
//        ListPopAdapter mListPopAdapter = new ListPopAdapter(context, list, R.layout.item_list_pop);
//        popListView.setAdapter(mListPopAdapter);


//        mAbTitleBar.setTitleTextDropDown(popView);

        title_back2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(context, B23_zhenxinhuaActivity.class);
                it.putExtra("jid", jid);
                it.putExtra("jicon", jicon);
                it.putExtra("jname", jname);
                it.putExtra("isInitiative", true);
                startActivity(it);
//                mAbTitleBar.showWindow(title_back2, popView, true);
            }
        });

//        popListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
//            @Override
//            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
//                switch (position) {
//                    case 0:
//                        Intent it = new Intent(context, B23_zhenxinhuaActivity.class);
//                        it.putExtra("jid", jid);
//                        it.putExtra("jicon", jicon);
//                        it.putExtra("jname", jname);
//                        it.putExtra("isInitiative",true);
//                        startActivity(it);
//                        mAbTitleBar.hideWindow();
//                        break;
//                    case 1:
//                        it = new Intent(context, E1_GiftShopActivity.class);
//                        it.putExtra("jid", jid);
//                        it.putExtra("jicon", jicon);
//                        it.putExtra("jname", jname);
//                        it.putExtra("isInitiative",true);
//                        startActivity(it);
//                        mAbTitleBar.hideWindow();
//                        break;
//                    case 2:
//                        AbToastUtil.showToast(context, "更多功能正在开发中");
//                        mAbTitleBar.hideWindow();
//                        break;
//                }
//            }
//        });


//        mAbTitleBar.setTitleText(jname);
//        mAbTitleBar.setLogo(R.drawable.home_search_left2);
//        mAbTitleBar.setTitleBarBackground(R.color.mainColor);
//
//        mAbTitleBar.setTitleBarGravity(Gravity.CENTER,Gravity.RIGHT);
//
//        View rightViewMore = mInflater.inflate(R.layout.more_btn, null);
//        mAbTitleBar.addRightView(rightViewMore);
//
//
//
//        View popView = mInflater.inflate(R.layout.list_pop, null);
//        ListView popListView = (ListView) popView.findViewById(R.id.pop_list);
//        List<AbMenuItem> list = new ArrayList<AbMenuItem>();
//        list.add(new AbMenuItem("真心话模式"));
//        list.add(new AbMenuItem("挑选真心话"));
//        list.add(new AbMenuItem("更多"));
//        ListPopAdapter mListPopAdapter = new ListPopAdapter(context, list,R.layout.item_list_pop);
//        popListView.setAdapter(mListPopAdapter);
//
////        mAbTitleBar.showWindow(rightViewMore,popView,true);
//        mAbTitleBar.setTitleTextDropDown(popView);


    }

    @Override
    protected void onPause() {
        super.onPause();
        if (flag.equals("0")) {
            PreferencesUtils.putInt(context, "liaoStatus", 0);

        }
    }

    @Override
    protected void onResume() {
        super.onResume();

        initFloatView();//可移动悬浮窗

        /***
         * liaoStatus（聊天状态）：0（程序在后台）；1（程序在前端显示，非聊天界面）；2（显示聊天界面）
         */
        PreferencesUtils.putInt(context, "liaoStatus", 2);
        int liaoStatus = PreferencesUtils.getInt(context, "liaoStatus");
        mLog.e("当前的聊天状态：liaoStatus=" + liaoStatus);


        mLog.e("恢复运行时读取的聊天记录：");
        datas = MsgDao.queryWithId(context, jid, cid);
        adapter.setLists(datas);
        adapter.setIcon(jicon);
        adapter.notifyDataSetChanged();
        if (datas != null) {

            list.setSelection(datas.size());
        }


    }


    private void initDubai() {
        RelativeLayout dubaiRL;
        TextView dubai_name;
        ImageView dubai_icon;
        final ImageView icon;
        TextView dubai_content;
        dubaiRL = (RelativeLayout) findViewById(R.id.dubai);
        dubai_name = (TextView) findViewById(R.id.dubai_name);
        dubai_icon = (ImageView) findViewById(R.id.dubai_icon);
        icon = (ImageView) findViewById(R.id.icon);
        dubai_content = (TextView) findViewById(R.id.dubai_content);

        dubai_name.setText(jname + "的内心独白");

        dubai_content.setText(qianming);

        ImageLoader imageLoader = ImageLoader.getInstance();

        imageLoader.loadImage(jicon, new ImageLoadingListener() {
            @Override
            public void onLoadingStarted(String s, View view) {

            }

            @Override
            public void onLoadingFailed(String s, View view, FailReason failReason) {

            }

            @Override
            public void onLoadingComplete(String s, View view, Bitmap bitmap) {
                icon.setBackgroundDrawable(AbImageUtil.bitmapToDrawable(bitmap));

            }

            @Override
            public void onLoadingCancelled(String s, View view) {

            }
        });

//        imageLoader.displayImage(jicon, icon);

        dubaiRL.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mLog.i("进入用户资料界面：jid=" + jid);
                Intent it = new Intent().setClass(context, B6_ziliaoActivity.class);
//                it.putExtra("jid", jid);
                it.putExtra("HerId", jid);
                startActivity(it);

            }
        });


    }

    /**
     * 改进的发送消息的方法
     */
    private void send() {
        //1..封装消息
        final String msg = input.getText().toString();

        final String msg2= EmojiFilter.filterEmoji(msg);



        String time = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date());
        final MSG bean = new MSG();
        bean.setJid(jid);
        bean.setCid(cid);
        bean.setContent(msg);
        bean.setTime(time);
        bean.setFlag(MSG.SEND);

        //2.配置其他
        datas.add(bean);
        adapter.setLists(datas);
        adapter.notifyDataSetChanged();
        list.setSelection(datas.size());
        input.setText("");

        //调用消息控制器，发送消息
        ChatModel.send(context, bean);
        PreferencesUtils.putBoolean(context, jid + "isZhuihui", false);//jid不追回

        //5.开启自动回复机制（8秒后启动线程）----图灵
        int temp=8;
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                //调用消息控制器，接受消息
//                ChatModel.setfindFaceLister(new ChatModel.findFaceLister() {
//                    @Override
//                    public void haveFindFace() {
//
//
//                    }
//                });
                ChatModel.receiveWithTuling(context, jid, cid, msg, new ChatModel.MsgLister() {
                    @Override
                    public void onRecive() {
                        //接受到消息后，刷新页面
                        datas = MsgDao.queryWithId(context, jid, cid);
                        adapter.setLists(datas);
                        adapter.notifyDataSetChanged();
                        list.setSelection(datas.size());
                        //接受一次消息，消耗Y币20
                        MemberModel.setGetUserLister(new MemberModel.GetUserLister() {
                            @Override
                            public void onSuccess(USER user) {
                                MemberModel.ybiSubtract(context, 20);


                            }

                            @Override
                            public void onFailure(int i, String s) {
                            }
                        });
                        MemberModel.getUSER(context);

                        //将A自增后，A%4==0时，弹出邀请玩真心话对话框
                        int A = PreferencesUtils.getInt(context, jid + "LiaoCi", 0);
                        A++;
                        PreferencesUtils.putInt(context, jid + "LiaoCi", A);
                        mLog.e(jid + "LiaoCi=自增后：（是否弹出邀请玩真心话对话框）" + A);
                        if ((A) % 4 == 0 && A > 0) {
                            new Handler().postDelayed(new Runnable() {
                                @Override
                                public void run() {

                                    //解决窗体异常
                                    Activity activity = C2_MsgActivity.this;
                                    while (activity.getParent() != null) {
                                        activity = activity.getParent();
                                    }
                                    try {
                                        DialogModel.toZhenxinhua(context, false, jid, jicon, jname);
                                    } catch (Exception e) {
                                        mLog.e("AlertDialog  Exception:" + e.getMessage());
                                    }


                                }
                            }, 2000);
                        }

                    }
                });
            }
        }, MyConfig.TulingAPI_Huifu);
    }

    private void tiaozhuanBaoyue() {

        mLog.e("弹出包月服务对话框");
        View mView = LayoutInflater.from(context).inflate(R.layout.dialog_vipfuwu, null);
//        AbDialogUtil.showDialog(mView);

        builder = new AlertDialog.Builder(context, R.style.my_dialog);
//        builder.setView(mView);
        alertDialog = builder.create();

        alertDialog.setView(mView, 0, 0, 0, 0);
        alertDialog.setCancelable(false);
        alertDialog.show();

        TextView title = (TextView) mView.findViewById(R.id.title);
        TextView content = (TextView) mView.findViewById(R.id.content);
        TextView quxiao = (TextView) mView.findViewById(R.id.quxiao);
        TextView kaitong = (TextView) mView.findViewById(R.id.kaitong);

        title.setText("包月服务");
        content.setText("立即开通包月服务，和心爱的她畅聊吧");

        quxiao.setVisibility(View.GONE);
        kaitong.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Intent it = new Intent().setClass(context, B15_faxinBaoyueActivity.class);
                startActivity(it);
                alertDialog.cancel();
            }
        });

    }

    /**
     * 弹出邀请玩真心话的对话框
     */

    AlertDialog.Builder builder;
    AlertDialog alertDialog;
//    private void tanchuZhenxinhua() {
//        AlertDialog.Builder builder;
//        final AlertDialog alertDialog;
//        View mView = LayoutInflater.from(context).inflate(R.layout.dialog_zhenxinhuayaoqing, null);
//        builder = new AlertDialog.Builder(context,R.style.zhenxinhua_dialog);
////        builder.setView(mView);
//        alertDialog = builder.create();
//
//        alertDialog.setView(mView, 0, 0, 0, 0);
//        alertDialog.setCancelable(false);
//        alertDialog.show();
//
//
//        TextView icon= (TextView) mView.findViewById(R.id.icon);
//        TextView quxiao = (TextView) mView.findViewById(R.id.quxiao);
//        TextView kaitong = (TextView) mView.findViewById(R.id.kaitong);
//
//        BitmapUtils bitmapUtils=new BitmapUtils(context);
//        bitmapUtils.display(icon,jicon);
//
//
//        kaitong.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//
//                Intent it = new Intent(context, B23_zhenxinhuaActivity.class);
//                it.putExtra("jid", jid);
//                it.putExtra("jicon", jicon);
//                it.putExtra("jname", jname);
//                startActivity(it);
//                alertDialog.cancel();
//            }
//        });
//
//
//    }


    private void initIntent() {
        Intent it = getIntent();
        jid = it.getStringExtra("jid");
        jname = it.getStringExtra("jname");
        jicon = it.getStringExtra("jicon");
        qianming = it.getStringExtra("qianming");
        flag = it.getStringExtra("flag");//是否是从弹出框进入
        cid = PreferencesUtils.getString(context, "cid");
        cname = PreferencesUtils.getString(context, "cname");
    }

    /**
     * 内容区域的监听
     */
    private void initContent() {


    }

    /**
     * 头部的监听
     */
    private void initHead() {
        //顶部
        back = (ImageView) findViewById(R.id.back);
        title = (TextView) findViewById(R.id.title);
        right = (TextView) findViewById(R.id.back2);


        title.setText(jname);
        back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

        right.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent it = new Intent(context, B23_zhenxinhuaActivity.class);
                it.putExtra("jid", jid);
                it.putExtra("jicon", jicon);
                it.putExtra("jname", jname);
                it.putExtra("isInitiative", true);
                startActivity(it);
            }
        });


    }


    private Runnable mRunnable = new Runnable() {
        public void run() {
            //更新界面
            mHandler.obtainMessage().sendToTarget();
            //每2秒执行一次
            mHandler.postDelayed(mRunnable, 2000);
        }

    };


    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(android.os.Message msg) {
            super.handleMessage(msg);
        }
    };

    /**
     * 接受机器人发送的消息的方法
     */
    private void recevie() {
        //调用消息控制类，接受消息
        ChatModel.setfindFaceLister(new ChatModel.findFaceLister() {
            @Override
            public void haveFindFace() {
                datas = MsgDao.queryWithId(context, jid, cid);
                adapter.setLists(datas);
                adapter.notifyDataSetChanged();
                list.setSelection(datas.size());
                input.setText("");
            }
        });
        ChatModel.receive(context, jid, cid);


    }


    /**
     * 脚部的监听
     */
    boolean isFirstLiao;//是否第一次聊天

    private void initFoot() {
        footer = (RelativeLayout) findViewById(R.id.footer);
        suoyao = (RelativeLayout) findViewById(R.id.suoyao);

        input = (EditText) findViewById(R.id.input);
        send = (TextView) findViewById(R.id.send);
        send.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                send.setClickable(false);
                final String msg= input.getText().toString();


                String uni=XHttpUtils.All2Unicode(msg);
                mLog.e("聊天内容：（转unicode后）"+uni);

                String cn=XHttpUtils.Unicode2Chinese(uni);
                mLog.e("聊天内容：（uni转中文后）"+cn);

//               if(EmojiFilter.containsEmoji(msg)){
//                   AbToastUtil.showToast(context,"当前版本不支持表情输入");
//                   return;
//               }

//                String c = EmojiFilter.filterEmoji(msgf);
//                char[] d = msgf.toCharArray();
//
//                mLog.e("聊天内容："+msgf);
//                mLog.e("聊天内容：(转字符数组)"+d);
//                mLog.e("聊天内容：（过滤表情后）"+c);
//                String msg=c;
//
//
//                String uni=StringEscapeUtils.unescapeHtml4(Html.toHtml(input.getText()));
//                mLog.e("聊天内容：（转unicode后）"+uni);


                if(!NetworkUtils.isNetworkAvailable(context)){
                    AbToastUtil.showToast(context,"请检查您的网络！");
                    return;
                }



                if (msg.equals("")) {
                    AbToastUtil.showToast(context, "聊天内容不能为空");
                    return;
                }

//                //判断当前用户是否可聊天
//                boolean isOver=PreferencesUtils.getBoolean(context, "isOver", false);
//                mLog.e("isOver="+isOver);
//                if(isOver){
//                    tiaozhuanBaoyue();
//                    return;
//                }
                //这里还要判断一下当前的会员类型（0未会员，1Y币，2）


                //判断是否可以发送消息
                ChatModel.getSendable(context, jid, new ChatModel.MCallback() {
                    @Override
                    public void onCallBack(int type) {
                        mLog.e("接受回调的参数：type=" + type);
                        send.setClickable(true);

                        if (type == ChatModel.canSend) {
                            //进入发送消息的实现方法
                            mLog.e("进入发送消息的实现方法");
                            send();
                        } else if (type == ChatModel.toSendMoney) {
                            //进入送话费的实现方法
                            mLog.e("进入送话费的实现方法");
//                            toSendMoney();
                            mLog.e("进入发送消息的实现方法");
                            send();

                        } else {
//                    //弹出调转到包月界面的对话框
//                    DialogModel.toBaoyue(context, "立即开通包月服务，和心爱的她畅聊吧");


                            //清空Y币
                            MemberModel.removeAllYbi(context);
                            mLog.e("进入下一收费项目");
                            mLog.e("jname=" + jname);

                            //解决窗体异常
                            Activity activity = C2_MsgActivity.this;
                            while (activity.getParent() != null) {
                                activity = activity.getParent();
                            }
                            try {
                                ChatModel.toNextMemberType(context, jname);
                            } catch (Exception e) {
                                mLog.e("AlertDialog  Exception:" + e.getMessage());
                            }


                        }

                    }
                });


//                //随机1~5秒后,机器人回复一条消息
//                new Handler().postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        recevie();
//
//                    }
//                }, 1000*(1+new Random().nextInt(5)));

            }
        });

    }

    /**
     * 去送话费的实现方法
     */
    private void toSendMoney() {
        Intent k1 = new Intent(context, paySuccessActivity.class);
        startActivity(k1);
    }


    /**
     * 通过图灵机器人获得回复
     *
     * @param info
     */
    private void getMessageWithTuling(String info) {
        String url = "";
        String weburl = "http://www.tuling123.com/openapi/api";
        String appkey = "5f20539703b7aac79e192fe025528ba9";
//        http://www.tuling123.com/openapi/api?key=5f20539703b7aac79e192fe025528ba9&info=%E5%8D%81%E5%88%86%E5%85%B3%E5%BF%83

        url = weburl + "?key=" + appkey + "&info=" + info;
        BaseModel.setCallBackLister(new BaseModel.CallBackLister() {
            @Override
            public String onCallBack(String url, String result) {

                return url;
            }
        });
        BaseModel.get(url);

    }


}
